using Microsoft.Extensions.Logging;
using ProtoBuf;

namespace SeataNet.Core.Serialization
{
    /// <summary>
    /// Protobuf序列化器
    /// </summary>
    public class ProtobufSerializer : ISerializer
    {
        private readonly ILogger<ProtobufSerializer> _logger;

        public ProtobufSerializer(ILogger<ProtobufSerializer> logger)
        {
            _logger = logger;
        }

        public SerializerType Type => SerializerType.Protobuf;

        public byte[] Serialize<T>(T obj)
        {
            try
            {
                if (obj == null)
                {
                    return Array.Empty<byte>();
                }

                using var stream = new MemoryStream();
                Serializer.Serialize(stream, obj);
                return stream.ToArray();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Protobuf序列化失败");
                throw;
            }
        }

        public T Deserialize<T>(byte[] data)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    return default;
                }

                using var stream = new MemoryStream(data);
                return Serializer.Deserialize<T>(stream);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Protobuf反序列化失败");
                throw;
            }
        }

        public byte[] Serialize(object obj, Type type)
        {
            try
            {
                if (obj == null)
                {
                    return Array.Empty<byte>();
                }

                using var stream = new MemoryStream();
                Serializer.Serialize(stream, obj);
                return stream.ToArray();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Protobuf序列化失败: {type.Name}");
                throw;
            }
        }

        public object Deserialize(byte[] data, Type type)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    return null;
                }

                using var stream = new MemoryStream(data);
                return Serializer.Deserialize(type, stream);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Protobuf反序列化失败: {type.Name}");
                throw;
            }
        }
    }
}
